package org.nobody.mallb2c.mallmember.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.nobody.common.utils.HttpUtils;
import org.nobody.mallb2c.mallmember.dao.MemberLevelDao;
import org.nobody.mallb2c.mallmember.entity.MemberLevelEntity;
import org.nobody.mallb2c.mallmember.exception.PhoneExistException;
import org.nobody.mallb2c.mallmember.exception.UsernameExistException;
import org.nobody.mallb2c.mallmember.vo.MemberLoginVo;
import org.nobody.mallb2c.mallmember.vo.MemberRegistVo;
import org.nobody.mallb2c.mallmember.vo.SocialUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.nobody.common.utils.PageUtils;
import org.nobody.common.utils.Query;

import org.nobody.mallb2c.mallmember.dao.MemberDao;
import org.nobody.mallb2c.mallmember.entity.MemberEntity;
import org.nobody.mallb2c.mallmember.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

  @Autowired
  MemberLevelDao memberLevelDao;

  @Override
  public PageUtils queryPage(Map<String, Object> params) {
    IPage<MemberEntity> page = this.page(
      new Query<MemberEntity>().getPage(params),
      new QueryWrapper<MemberEntity>()
    );

    return new PageUtils(page);
  }

  @Override
  public void regist(MemberRegistVo vo) {
    MemberEntity memberEntity = new MemberEntity();

    //设置默认等级
    MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
    memberEntity.setLevelId(levelEntity.getId());

    //检查用户名和手机号是否唯一
    checkPhoneUnique(vo.getPhone());
    checkUsernameUnique(vo.getUserName());

    memberEntity.setMobile(vo.getPhone());
    memberEntity.setUsername(vo.getUserName());
    memberEntity.setNickname(vo.getUserName()); //默认昵称和用户名一样

    //密码要进行加密存储
    BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
    String encode = bCryptPasswordEncoder.encode(vo.getPassword());
    memberEntity.setPassword(encode);

    //其他的默认信息

    //保存
    this.baseMapper.insert(memberEntity);
  }

  @Override
  public void checkPhoneUnique(String phone) throws PhoneExistException{
    MemberDao memberDao = this.baseMapper;
    Integer mobile = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
    if (mobile > 0) {
      throw new PhoneExistException();
    }
  }

  @Override
  public void checkUsernameUnique(String username) throws UsernameExistException{
    MemberDao memberDao = this.baseMapper;
    Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
    if (count > 0) {
      throw new UsernameExistException();
    }
  }

  @Override
  public MemberEntity login(MemberLoginVo vo) {
    String loginacct = vo.getLoginacct();
    String password = vo.getPassword();

    //1、去数据库查询
    MemberDao memberDao = this.baseMapper;
    MemberEntity entity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));
    if (entity == null) {
      //登录失败
      return null;
    }else{
      String passwordDb = entity.getPassword();
      BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
      boolean b = bCryptPasswordEncoder.matches(password, passwordDb);
      if(b){
        return entity;
      }else{
        return null;
      }
    }
  }

    @Override
    public MemberEntity login(SocialUser socialUser){
      System.out.println("login~~~~~~~~~~~~~~~~~~~~");
      //登录和注册合并逻辑
      String uid = socialUser.getUid();
      //1、判断当前社交用户是否已经注册过
      MemberDao memberDao = this.baseMapper;
      MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
      if (memberEntity != null) {
        System.out.println("1111111111111111111");
        //用户已经注册了 更新access_token
        MemberEntity update = new MemberEntity();
        update.setId(memberEntity.getId());
        update.setAccessToken(socialUser.getAccess_token());
        update.setExpiresIn(socialUser.getExpires_in());
        memberDao.updateById(update);

        memberEntity.setAccessToken(socialUser.getAccess_token());
        memberEntity.setExpiresIn(socialUser.getExpires_in());

        return memberEntity;
      }else{
        System.out.println("2222222222222222222");
        //2、 没有查到当前社交用户对应的记录,我们就需要注册一个
        MemberEntity regist = new MemberEntity();
        try {
          //3、 查询当前社交用户的社交账号信息(昵称,性别等)
          Map<String, String> query = new HashMap<>();
          query.put("access_token", socialUser.getAccess_token());
          query.put("uid", socialUser.getUid());
          HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);
          if (response.getStatusLine().getStatusCode() == 200) {
            String json = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSON.parseObject(json); //太复杂了 也可以不传类型 直接parseObject
            System.out.println("jsonObject:"+jsonObject);
            String name = jsonObject.getString("name");
            String gender = jsonObject.getString("gender");
            //...
            regist.setNickname(name);
            regist.setGender("m".equals(gender) ? 1 : 0);
            //....
          }
        } catch (Exception e) {
          System.out.println("e~!~~~~:"+e);
        }

        //↓下面是三个信息 无论如何也要获取的
        regist.setSocialUid(socialUser.getUid());
        regist.setAccessToken(socialUser.getAccess_token());
        regist.setExpiresIn(socialUser.getExpires_in());
        memberDao.insert(regist);

        return regist;
      }
    }

}
